package com.pbase.data.http;


import java.util.concurrent.TimeUnit;

import androidx.annotation.NonNull;
import okhttp3.OkHttpClient;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava3.RxJava3CallAdapterFactory;

/**
 * Retrofit 实例生成
 */
public class RetrofitClient {

    private static Retrofit retrofit;


    private static volatile RetrofitClient instance;


    public static RetrofitClient getInstance(@NonNull RetrofitBuilderTool tool) {
        if (instance == null) {
            synchronized (RetrofitClient.class) {
                if (instance == null) {
                    instance = new RetrofitClient(tool);
                }
            }
        }
        return instance;
    }
//OkHttpClient build -- retrofit build
    private RetrofitClient(RetrofitBuilderTool tool) {
        if (tool == null) {
            tool = new RetrofitBuilderTool();
        }
        OkHttpClient.Builder build = new OkHttpClient.Builder();
        if (tool.buildCookieJar() != null) {
            build.cookieJar(tool.buildCookieJar());
        }
        if (tool.buildCache() != null) {
            build.cache(tool.buildCache());
        }
        if (tool.buildHeadInterceptor() != null) {
            build.addInterceptor(tool.buildHeadInterceptor());
        }
        if (tool.buildCacheInterceptor() != null) {
            build.addInterceptor(tool.buildCacheInterceptor());
        }
        if (tool.buildSSLParams() != null) {

            build.sslSocketFactory(tool.buildSSLParams().sSLSocketFactory,
                    tool.buildSSLParams().trustManager);
        }
        if (tool.buildLoggingInterceptor() != null) {
            build.addInterceptor(tool.buildLoggingInterceptor());
        }
        build.connectTimeout(tool.connectTimeout(), TimeUnit.SECONDS);
        build.writeTimeout(tool.writeTimeout(), TimeUnit.SECONDS);
        build.readTimeout(tool.readTimeout(), TimeUnit.SECONDS);
        if (tool.buildConnectionPool() != null) {
            build.connectionPool(tool.buildConnectionPool());
        }
        OkHttpClient  okHttpClient = build.build();
        retrofit = new Retrofit.Builder()
                .client(okHttpClient)
                .addConverterFactory(tool.buildConverterFactory())
                .addCallAdapterFactory(RxJava3CallAdapterFactory.create())
                .baseUrl(tool.baseUrl())
                .build();

    }
//service create
    public <T> T create(final Class<T> service) {
        if (service == null) {
            throw new RuntimeException("Api service is null!");
        }
        return retrofit.create(service);
    }
}
